<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\Exception;
use think\facade\Cache;
use think\facade\Event;
use app\common\controller\Config;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,parent_id,level_id,team_id');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,parent_id,level_id,team_id')->with(['level', 'team']);
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid'      => $parentId,
                'code'     => $parentCode,
                'algebra'  => 1,
                'new_uid'  => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,"' . $new_code . '" as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }



    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            foreach ($list as $item) {
                $min_total = User::geMinTeam($item->user->id);
                $user_total = User::geTpCount($item->user);
                $level = Team::where('id', '>', $item->user->team_id)
                    ->where('team_money', '<=', $min_total)
                    ->where('zt_count', '<=', $user_total)
                    ->order('id', 'asc')
                    ->find();
                    // print('<pre>');print_r($level);die;
                if ($level) {
                    User::update(['team_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 新增业绩
     */
    public static function newPerformance($amount)
    {
        $sys = Config::lists();
        $info = Bonus::whereDay('create_time')->find();
        if (empty($info)) {
            $info = Bonus::create([
                'title' => date('Y年m月d日', time()) . '董事分红业绩',
                'money' => $amount,
                'bonus' => round($amount * $sys['tp_3'], 2),
            ]);
        } else {
            $info->money += $amount;
            $info->bonus += round($amount * $sys['tp_3'], 2);
            $info->save();
        }
    }
    /**
     * 奖金
     */
    public static function bonus($money, $user, $type)
    {
        $sys = Config::lists();
        try {
            switch ($type) {
                case 1:
                    /**
                     * 销售奖
                     */
                    if ($user->parent_id != 0) {
                        $tp_money = self::getBurn($money,$user->parent_id);
                        $tp_2 = 0;
                        $tp_2 = round($money * $sys['tp_2'], 2);
                        if ($tp_2 > 0) {
                            Target::Account()->basics($user->parent_id, 'bonus_2', $tp_2, '销售奖', '+')
                                ->createBonus($user->id, 2);
                        }
                    }
                    $toal_money = $tp_2;
                    break;
                case 2:
                    /**
                     * 分享奖
                     */
                    $share = 0;
                    $list =  self::getTeamList($user, 5);
                    // print('<pre>');print_r($list);die; 
                    if (!empty($list)) {
                        foreach ($list as $v) {
                            // $top_share = self::getBurn($money,$v['uid']);
                            $share = self::getUserRed($v['uid'], round($money * $v['bl'], 2));
                            if ($share > 0) {
                                Target::Account()->basics($v['uid'], 'bonus_2', $share, '分享奖释放', '-')
                                    ->createNormal($user->id);

                                Target::Account()->basics($v['uid'], 'bonus_3', $share, '分享奖', '+')
                                    ->createBonus($user->id, 3);
                            }
                        }
                    }
                    $toal_money = $share;
                    break;
                case 3:
                    /**
                     * 团建奖
                     */
                    $tp_3 = 0;
                    $tp_4 = 0;
                    $list = self::getLevelInfo($user->team_id, $user->id);
                    if (!empty($list)) {
                        foreach ($list as $v) {
                            $tp_3 = self::getUserRed($v['uid'], round($money * $v['bl'], 2));
                            // print('<pre>');print_r($tp_3);die;
                            if ($tp_3 > 0) {
                                Target::Account()->basics($v['uid'], 'bonus_2', $tp_3, '团建奖释放', '-')
                                    ->createNormal($user->id);
                                Target::Account()->basics($v['uid'], 'bonus_3', $tp_3, '团建奖', '+')
                                    ->createBonus($user->id, 4);
                            }
                            if ($v['pid'] != 0) {
                                $tp_4 = self::getUserRed($v['pid'], round($tp_3 * $sys['tp_4'], 2));
                                if ($tp_4 > 0) {
                                    Target::Account()->basics($v['pid'], 'bonus_2', $tp_4, '平级奖释放', '-')
                                        ->createNormal($user->id);
                                    Target::Account()->basics($v['pid'], 'bonus_3', $tp_4, '平级奖', '+')
                                        ->createBonus($user->id, 6);
                                }
                            }
                        }
                    }
                    $toal_money  = $tp_3 + $tp_4;
                    break;
                default:
                    return ['code' => -1, 'msg' => '系统错误'];
                    break;
            }
            if ($toal_money > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $toal_money]);
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 获取团队列表
     */
    public static function getTeamList($user, $level = 1)
    {
        $arr = [];
        try {
            $list = parent::with('user')->where('new_uid', $user->id)->where('algebra', '<=', $level)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            foreach ($list as $k => $v) {
                $num = self::getTeamNum($v->uid);
                $count = Share::where('algebra', $v->algebra)->find();
                if ($num >= $count['count']) {
                    $data['uid'] = $v->uid;
                    $data['bl'] = $count['award'];
                    $arr[] = $data;
                }
            }
            return $arr;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取直推人数
     */
    public static function getTeamNum($uid)
    {
        $num = 0;
        try {
            $list = parent::where(['uid' => $uid, 'algebra' => 1])->column('new_uid');
            $num = User::whereIn('id', $list)->where('is_active', 2)->count();
            return $num;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 级差奖励
     */
    public static function getLevelInfo($level, $uid)
    {
        try {
            $team_id =  $level;
            $list = parent::where('new_uid', $uid)->with(['user'])->order('algebra asc')->select();
            foreach ($list as $k => $v) {
                if ($v->user->team_id > $team_id && $v->user->team_id <= 5) {
                    $nowmoney = Team::where('id', $v->user->team_id)->value('award');
                    $upmoney = Team::where('id', $team_id)->value('award');
                    $data['uid'] = $v->user->id;
                    $data['bl'] = $nowmoney - $upmoney;
                    $data['pid'] = self::getLevelUser($v->user->team_id, $v->user->id);
                    $ids[] = $data;
                    $team_id = $v->user->team_id;
                }
            }
            if (!empty($ids)) {
                return $ids;
            } else {
                return [];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取平级用户
     */
    public static function getLevelUser($level, $uid)
    {
        try {
            $id = 0;
            $list = parent::where('new_uid', $uid)->with(['user'])->order('algebra asc')->select();
            foreach ($list as $k => $v) {
                if ($v->user->team_id == $level) {
                    return $v->user->id;
                }
            }
            return $id;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取用户红积分
     */
    public static function getUserRed($uid, $money)
    {
        try {
            $moneys = 0;
            $red = User::where('id', $uid)->with('assets')->find();
            if ($red->assets->bonus_2 > 0) {
                if ($money > $red->assets->bonus_2) {
                    $moneys = $red->assets->bonus_2;
                } else {
                    $moneys = $money;
                }
            }
            return $moneys;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 静态释放
     */
    public static function staticRelease()
    {
        $sys = Config::lists();
        try {
            $toal = 0;
            $list  = Assets::where('bonus_2', '>', 0)->select();
            foreach ($list as $k => $v) {
                $money = User::where('id', $v['uid'])->value('money');
                $user = User::where('id', $v['uid'])->find();
                $level_tp = Level::where(['id'=>$user->level_id])->value('tp_1');
                if ($money > 0) {
                    $tp_1 = self::getUserRed($v['uid'], round($level_tp * $money, 2));
                    if ($tp_1 > 0) {
                        /**
                         * 团队奖
                         */
                        Relation::bonus($tp_1, $user, 3);
                        Target::Account()->basics($v['uid'], 'bonus_2', $tp_1, '静态释放', '-')
                            ->createNormal();
                        Target::Account()->basics($v['uid'], 'bonus_3', $tp_1, '静态奖', '+')
                            ->createBonus(0, 1);
                            $toal += $tp_1; 
                    }
                }
            }
            if($toal>0){
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $toal]);
            }
            return ['code' => 1, 'msg' => '释放成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取烧伤值
     */
    public static function getBurn($money, $uid)
    {
        try {
            $red = User::where('id', $uid)->find();
            if ($red->money < $money) {
                $money = $red->money;
            }
            return $money;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
